package com.hunter.applearn.activity

import android.os.Bundle
import android.util.Log
import android.view.ViewTreeObserver

import androidx.activity.enableEdgeToEdge
import androidx.fragment.app.Fragment


import com.hunter.applearn.R
import com.hunter.applearn.databinding.ActivityHomeBinding
import com.hunter.applearn.fragment.FavourFragment
import com.hunter.applearn.fragment.HomeFragment
import com.hunter.applearn.fragment.UserFragment


class HomeActivity : BaseActivity() {
    private lateinit var binding: ActivityHomeBinding
    private var currentTabId = R.id.nav_home

    // Fragment缓存
    private val fragmentMap = mutableMapOf<Int, Fragment>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityHomeBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 1. 设置点击监听器
        setupClickListeners()

        // 2. 初始化默认显示首页Fragment
//        switchFragment(R.id.nav_home)

        // 3. 设置初始选中状态
//        updateTabAppearance()

        // 使用ViewTreeObserver确保布局完成后再加载Fragment
//        binding.fragmentContainer.viewTreeObserver.addOnGlobalLayoutListener(object :
//            ViewTreeObserver.OnGlobalLayoutListener {
//            override fun onGlobalLayout() {
//                binding.fragmentContainer.viewTreeObserver.removeOnGlobalLayoutListener(this)
//                // 2. 初始化默认显示首页Fragment
//                switchFragment(R.id.nav_home)
//                // 3. 设置初始选中状态
//                updateTabAppearance()
//            }
//        })

        // 确保在UI完全加载后再初始化Fragment
//        window.decorView.post {
//            switchFragment(R.id.nav_home)
//            updateTabAppearance()
//        }

        // 强制化初始fragment
        initializeDefaultFragment()
    }


    override fun onDestroy() {
        super.onDestroy()
        // 清理Fragment缓存，避免内存泄漏
        fragmentMap.clear()
    }

    /**
     * 按钮的点击事件
     *
     */
    private fun setupClickListeners() {
        // 首页点击事件
        binding.navHome.setOnClickListener {
            Log.e("fargment", "点击首页")
            // 切换fragment
            switchFragment(R.id.nav_home)
            // 更新tab选中状态
            updateTabAppearance()

        }
        // 收藏点击事件
        binding.navFavour.setOnClickListener {
            Log.e("fargment", "点击收藏")
            switchFragment(R.id.nav_favour)
            updateTabAppearance()
        }
        // 用户点击事件
        binding.navUser.setOnClickListener {
            Log.e("fargment", "点击用户")
            switchFragment(R.id.nav_user)
            updateTabAppearance()
        }
    }

    /**
     * 切换Fragment
     *
     */
    private fun switchFragment(tabId: Int) {
        // 如果当前已经是目标Fragment，不做处理
        if (currentTabId == tabId) return

        val fragment = getFragmentInstance(tabId)
        // 开启fragmentManager事务
        val transaction = supportFragmentManager.beginTransaction()
        // 设置动画
        transaction.setCustomAnimations(
            android.R.anim.fade_in,
            android.R.anim.fade_out
        )
        // 切换到传入的fragment
        transaction.replace(R.id.fragment_container, fragment)
        // 允许 FragmentManager 优化执行顺序，提高性能
        transaction.setReorderingAllowed(true)
        // 提交事务
        transaction.commit()
        // 切换currentTabId为当前tabId 状态管理集中
        currentTabId = tabId
    }

    /**
     * 更新tab选中状态
     *
     */
    private fun updateTabAppearance() {
        // 设置当前选中图标状态
        // 逻辑：currentTabId == R.id.nav_home是一个布尔表达式返回true或false
        binding.navHome.isSelected = currentTabId == R.id.nav_home
        binding.navFavour.isSelected = currentTabId == R.id.nav_favour
        binding.navUser.isSelected = currentTabId == R.id.nav_user
    }

    /**
     * 获取fragment缓存实例
     *
     */
    private fun getFragmentInstance(tabId: Int): Fragment {
        // 如果已存在实例，直接返回，否则创建新实例并缓存
        return fragmentMap.getOrPut(tabId) {
            when (tabId) {
                R.id.nav_home -> HomeFragment()
                R.id.nav_favour -> FavourFragment()
                R.id.nav_user -> UserFragment()
                else -> HomeFragment()
            }
        }
    }

    /**
     * 初始化fragment
     */
    private fun initializeDefaultFragment() {
        // 强制初始化首页Fragment，忽略currentTabId检查
        Log.e("HomeActivity", "初始化默认Fragment")
        val fragment = getFragmentInstance(R.id.nav_home)

        supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, fragment)
            .commitNowAllowingStateLoss() // 使用commitNowAllowingStateLoss确保立即执行

        currentTabId = R.id.nav_home
        updateTabAppearance()

        Log.e("HomeActivity", "默认Fragment初始化完成")
    }

}